package util.android.task;

import java.util.Calendar;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

import android.os.Handler;

public class TestAndroidTask {
	
		
	
	//beep cada 10 segundos
	//http://examples.javacodegeeks.com/android/core/activity/android-timertask-example/
	public static void ejemplo1_timer() {
		
		final Handler handler = new Handler(); 
		
        TimerTask tarea = new TimerTask() {			
			@Override
			public void run() {				
				handler.post(new Runnable() {						
					@Override
					public void run() {
						System.out.println("beep");
					}
				});					
			}
		};
		
		Timer timer = new Timer(); 
		Calendar fechaInicial = Calendar.getInstance();
        timer.schedule(
          tarea,//TAREA
          fechaInicial.getTime(),// Desde ahora
          1000 * 10 //Cada 10 segundos
        );
	}
	
	//Timer tiene algunas deventajas que son resueltas por ScheduledThreadPoolExecutor. Entonces, no es la mejor opcion
	//http://stackoverflow.com/questions/14376470/scheduling-recurring-task-in-android
	//http://developer.android.com/reference/java/util/concurrent/ScheduledExecutorService.html
	//beep cada 10 segundos durante 1 hora
	public static void ejemplo2_ScheduledThreadPoolExecutor() {
		
		final Handler handler = new Handler();
		
		//final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
		final ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();
		
		final Runnable beeper = new Runnable() {
			public void run() {			
				//System.out.println("beep");
				
				handler.post(new Runnable() {						
					@Override
					public void run() {
						System.out.println("beep");
					}
				});	
			}
		};
	     
		//repeticion de la tarea
		@SuppressWarnings("rawtypes")
		final ScheduledFuture beeperHandle = scheduler.scheduleAtFixedRate(beeper, 10, 10, TimeUnit.SECONDS);
		
		//finalizacion de la tarea
		scheduler.schedule(new Runnable() {
		   public void run() {
			 //beeperHandle.cancel(true);
			   handler.post(new Runnable() {						
					@Override
					public void run() {
						beeperHandle.cancel(true);
					}
				});	
			    
		   }
		}, 60 * 60, TimeUnit.SECONDS);
		
	}
}
